<?php

namespace Biz\service\advertisement\db;

use Doraemon\cache\PositionModule\Rules;
use Doraemon\model\Position\PositionRules;
use Doraemon\service\position\UserProfileModule;

class PositionRulesCache extends Cache
{

    public static function cache($id, $module = 0)
    {
        $instance = self::getInstance();
        // 取缓存
        if (!is_array($id)) $id = [$id];

        list($oldCache, $noCache) = $instance->getCache($id, $module);

        $cache = [];
        if ($noCache) {
            // 获取数据
            $cache = $instance->getData($noCache, $module);
            // 从方法中拿到需要的数据
            if (!$instance->isEmpty($cache)) {
                // 存缓存
                $instance->setCache($module, $cache);
            }
        }
        return $oldCache + $cache;
    }
    public function getCache($id, $module = 0): array
    {
        return Rules::mGetItems($id, Rules::getPrefixKey($module));
    }

    public function setCache($id, $data)
    {
        Rules::mSetItems($data, 0, Rules::getPrefixKey($id));
    }

    public function getData($id, $module = 0): array
    {
        $where = [
            'position_base_info_id' => $id,
            'module_type' => $module,
            'rule_status' => PositionRules::STATUS_NORMAL,
        ];
        $list = PositionRules::select('*', $where);
        $temp = [];
        if ($list) {
            foreach ($list as $value) {
                $temp[$value['position_base_info_id']][$value['rule_type']] = UserProfileModule::decode($value['rule_type'], $value['rule_value']);
            }
        }
        $response = [];
        foreach ($id as $v) {
            $response[$v] = $temp[$v] ?? [];
        }
        return $response;
    }

    public function isEmpty($cache): bool
    {
        return empty($cache);
    }
}